

import React, { useState, useEffect, useRef } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import styles from './styles.module.css';
import { FoodItem, RecognitionResult, InputMethodTab, FoodCategory } from './types';
import { foodAPI } from '../../services/api';
import { getAuthToken } from '../../utils/auth';

// 分类名称映射
const categoryNames: Record<FoodCategory, string> = {
  all: '全部食物',
  grains: '谷物类',
  meat: '肉类',
  vegetables: '蔬菜类',
  fruits: '水果类',
  dairy: '乳制品',
  snacks: '零食类'
};

const FoodSearchPage: React.FC = () => {
  const navigate = useNavigate();
  
  // 状态管理
  const [activeTab, setActiveTab] = useState<InputMethodTab>('text-search');
  const [textSearchInput, setTextSearchInput] = useState('');
  const [globalSearchInput, setGlobalSearchInput] = useState('');
  const [searchResults, setSearchResults] = useState<FoodItem[]>([]);
  const [selectedImage, setSelectedImage] = useState<string | null>(null);
  const [recognitionResults, setRecognitionResults] = useState<RecognitionResult[]>([]);
  const [activeCategory, setActiveCategory] = useState<FoodCategory>('all');
  const [isDragOver, setIsDragOver] = useState(false);
  const [foods, setFoods] = useState<FoodItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  
  const imageUploadRef = useRef<HTMLInputElement>(null);

  // 设置页面标题
  useEffect(() => {
    const originalTitle = document.title;
    document.title = '食算 - 添加食物';
    return () => { document.title = originalTitle; };
  }, []);

  // 加载食物数据
  useEffect(() => {
    const loadFoods = async () => {
      const token = getAuthToken();
      if (!token) {
        setError('请先登录');
        return;
      }

      setLoading(true);
      try {
        const foodsData = await foodAPI.getFoods();
        // 转换API数据格式为前端需要的格式
        const convertedFoods: FoodItem[] = foodsData.map((food: any) => ({
          id: food.id.toString(),
          name: food.name,
          category: mapCategory(food.category),
          calories: food.calories,
          protein: food.protein,
          carb: food.carb,
          fat: food.fat,
          unit: food.unit,
          image: getFoodImage(food.name)
        }));
        setFoods(convertedFoods);
      } catch (err) {
        setError('加载食物数据失败');
        console.error('Error loading foods:', err);
      } finally {
        setLoading(false);
      }
    };

    loadFoods();
  }, []);

  // 分类映射函数
  const mapCategory = (category: string): FoodCategory => {
    const categoryMap: Record<string, FoodCategory> = {
      '主食': 'grains',
      '蛋白质': 'meat',
      '蔬菜': 'vegetables',
      '水果': 'fruits',
      '乳制品': 'dairy',
      '零食': 'snacks'
    };
    return categoryMap[category] || 'all';
  };

  // 获取食物图片
  const getFoodImage = (foodName: string): string => {
    const imageMap: Record<string, string> = {
      '苹果': 'https://s.coze.cn/image/e5UUJQ8-Uhk/',
      '香蕉': 'https://s.coze.cn/image/TtUwWwSZEgw/',
      '米饭': 'https://s.coze.cn/image/LVNlSLN25Ww/',
      '鸡蛋': 'https://s.coze.cn/image/m5P-2VDBxz4/',
      '鸡胸肉': 'https://s.coze.cn/image/F6-ocO41L_0/',
      '牛奶': 'https://s.coze.cn/image/ITIsmNcyqbY/',
      '面包': 'https://s.coze.cn/image/CFGDv6V7gNA/',
      '牛肉': 'https://s.coze.cn/image/XuPw-oLqrJI/',
      '西兰花': 'https://s.coze.cn/image/bk8TMBM3MnM/',
      '三文鱼': 'https://s.coze.cn/image/C3k89Fe9CbI/'
    };
    return imageMap[foodName] || 'https://s.coze.cn/image/LVNlSLN25Ww/';
  };

  // 处理标签页切换
  const handleTabChange = (tab: InputMethodTab) => {
    setActiveTab(tab);
  };

  // 处理文字搜索
  const handleTextSearch = async () => {
    const searchTerm = textSearchInput.trim().toLowerCase();
    
    if (!searchTerm) {
      setSearchResults([]);
      return;
    }

    setLoading(true);
    try {
      const foodsData = await foodAPI.getFoods(searchTerm);
      // 转换API数据格式为前端需要的格式
      const convertedFoods: FoodItem[] = foodsData.map((food: any) => ({
        id: food.id.toString(),
        name: food.name,
        category: mapCategory(food.category),
        calories: food.calories,
        protein: food.protein,
        carb: food.carb,
        fat: food.fat,
        unit: food.unit,
        image: getFoodImage(food.name)
      }));
      setSearchResults(convertedFoods);
    } catch (err) {
      setError('搜索食物失败');
      console.error('Error searching foods:', err);
    } finally {
      setLoading(false);
    }
  };

  // 处理文字搜索回车
  const handleTextSearchKeyPress = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter') {
      handleTextSearch();
    }
  };

  // 处理全局搜索回车
  const handleGlobalSearchKeyPress = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter') {
      const searchTerm = globalSearchInput.trim();
      if (searchTerm) {
        setTextSearchInput(searchTerm);
        setActiveTab('text-search');
        // 延迟一点执行搜索，让UI有时间更新
        setTimeout(() => {
          handleTextSearch();
        }, 100);
      }
    }
  };

  // 处理图片上传
  const handleImageUpload = (file: File) => {
    if (!file.type.startsWith('image/')) {
      alert('请选择图片文件');
      return;
    }

    if (file.size > 5 * 1024 * 1024) {
      alert('文件大小不能超过5MB');
      return;
    }

    const reader = new FileReader();
    reader.onload = (e) => {
      if (e.target?.result) {
        setSelectedImage(e.target.result as string);
        setRecognitionResults([]);
      }
    };
    reader.readAsDataURL(file);
  };

  // 处理上传区域点击
  const handleUploadAreaClick = () => {
    imageUploadRef.current?.click();
  };

  // 处理文件选择
  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files && e.target.files.length > 0) {
      handleImageUpload(e.target.files[0]);
    }
  };

  // 处理拖拽事件
  const handleDragOver = (e: React.DragEvent<HTMLDivElement>) => {
    e.preventDefault();
    setIsDragOver(true);
  };

  const handleDragLeave = (e: React.DragEvent<HTMLDivElement>) => {
    e.preventDefault();
    setIsDragOver(false);
  };

  const handleDrop = (e: React.DragEvent<HTMLDivElement>) => {
    e.preventDefault();
    setIsDragOver(false);
    const files = e.dataTransfer.files;
    if (files.length > 0) {
      handleImageUpload(files[0]);
    }
  };

  // 移除图片
  const handleRemoveImage = () => {
    setSelectedImage(null);
    setRecognitionResults([]);
    if (imageUploadRef.current) {
      imageUploadRef.current.value = '';
    }
  };

  // 开始识别
  const handleStartRecognition = () => {
    console.log('需要调用第三方接口实现图片识别功能');
    // 模拟识别结果
    const mockResults: RecognitionResult[] = [
      { food: mockFoods[1], confidence: 0.92 },
      { food: mockFoods[2], confidence: 0.78 },
      { food: mockFoods[0], confidence: 0.65 }
    ];

    setRecognitionResults(mockResults);
  };

  // 处理分类切换
  const handleCategoryChange = (category: FoodCategory) => {
    setActiveCategory(category);
  };

  // 获取分类筛选后的食物
  const getFilteredFoods = () => {
    if (activeCategory === 'all') {
      return foods;
    }
    return foods.filter(food => food.category === activeCategory);
  };

  // 处理食物项点击
  const handleFoodItemClick = (foodId: string) => {
    navigate(`/food-detail?foodId=${foodId}`);
  };

  // 渲染食物项
  const renderFoodItem = (food: FoodItem) => (
    <div 
      key={food.id}
      className={`${styles.foodItem} flex items-center justify-between p-4 border border-border-light rounded-lg cursor-pointer transition-colors`}
      onClick={() => handleFoodItemClick(food.id)}
    >
      <div className="flex items-center space-x-4">
        <img 
          src={food.image} 
          alt={food.name} 
          className="w-12 h-12 rounded-lg object-cover" 
          data-category="食物"
        />
        <div>
          <h4 className="font-medium text-text-primary">{food.name}</h4>
          <p className="text-sm text-text-secondary">{categoryNames[food.category as FoodCategory]}</p>
        </div>
      </div>
      <div className="text-right">
        <p className="font-semibold text-text-primary">{food.calories} kcal/100g</p>
      </div>
    </div>
  );

  // 渲染识别结果项
  const renderRecognitionResult = (result: RecognitionResult) => (
    <div 
      key={result.food.id}
      className={`${styles.foodItem} flex items-center justify-between p-4 border border-border-light rounded-lg cursor-pointer transition-colors`}
      onClick={() => handleFoodItemClick(result.food.id)}
    >
      <div className="flex items-center space-x-4">
        <img 
          src={result.food.image} 
          alt={result.food.name} 
          className="w-12 h-12 rounded-lg object-cover" 
          data-category="食物"
        />
        <div>
          <h4 className="font-medium text-text-primary">{result.food.name}</h4>
          <p className="text-sm text-text-secondary">置信度: {(result.confidence * 100).toFixed(0)}%</p>
        </div>
      </div>
      <div className="text-right">
        <p className="font-semibold text-text-primary">{result.food.calories} kcal/100g</p>
      </div>
    </div>
  );

  return (
    <div className={styles.pageWrapper}>
      {/* 顶部导航栏 */}
      <header className="fixed top-0 left-0 right-0 bg-white border-b border-border-light h-16 z-50">
        <div className="flex items-center justify-between h-full px-6">
          {/* Logo和产品名称 */}
          <div className="flex items-center space-x-3">
            <div className="w-8 h-8 bg-primary rounded-lg flex items-center justify-center">
              <i className="fas fa-utensils text-white text-sm"></i>
            </div>
            <h1 className="text-xl font-bold text-text-primary">食算</h1>
          </div>
          
          {/* 全局搜索框 */}
          <div className="flex-1 max-w-md mx-8">
            <div className="relative">
              <input 
                type="text" 
                placeholder="搜索食物..." 
                value={globalSearchInput}
                onChange={(e) => setGlobalSearchInput(e.target.value)}
                onKeyPress={handleGlobalSearchKeyPress}
                className="w-full pl-10 pr-4 py-2 border border-border-light rounded-lg focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"
              />
              <i className="fas fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-text-secondary"></i>
            </div>
          </div>
          
          {/* 右侧操作区 */}
          <div className="flex items-center space-x-4">
            {/* 消息通知 */}
            <button className="relative p-2 text-text-secondary hover:text-primary">
              <i className="fas fa-bell text-lg"></i>
              <span className="absolute -top-1 -right-1 w-3 h-3 bg-danger rounded-full"></span>
            </button>
            
            {/* 用户头像和下拉菜单 */}
            <div className="relative">
              <button className="flex items-center space-x-2 p-1 rounded-lg hover:bg-gray-100">
                <img 
                  src="https://s.coze.cn/image/D9VOuIuPJXQ/" 
                  alt="用户头像" 
                  className="w-8 h-8 rounded-full" 
                  data-category="人物"
                />
                <span className="text-sm text-text-primary">张三</span>
                <i className="fas fa-chevron-down text-xs text-text-secondary"></i>
              </button>
            </div>
          </div>
        </div>
      </header>

      {/* 左侧菜单 */}
      <aside className={`fixed left-0 top-16 bottom-0 w-60 bg-white border-r border-border-light ${styles.sidebarTransition} z-40`}>
        <nav className="p-4">
          <ul className="space-y-2">
            <li>
              <Link 
                to="/home" 
                className={`${styles.navItem} flex items-center space-x-3 px-4 py-3 rounded-lg text-text-secondary`}
              >
                <i className="fas fa-home text-lg"></i>
                <span className="font-medium">首页</span>
              </Link>
            </li>
            <li>
              <Link 
                to="/food-search" 
                className={`${styles.navItem} ${styles.navItemActive} flex items-center space-x-3 px-4 py-3 rounded-lg`}
              >
                <i className="fas fa-search text-lg"></i>
                <span className="font-medium">食物搜索</span>
              </Link>
            </li>
            <li>
              <Link 
                to="/record-list" 
                className={`${styles.navItem} flex items-center space-x-3 px-4 py-3 rounded-lg text-text-secondary`}
              >
                <i className="fas fa-list text-lg"></i>
                <span className="font-medium">饮食记录</span>
              </Link>
            </li>
            <li>
              <Link 
                to="/history" 
                className={`${styles.navItem} flex items-center space-x-3 px-4 py-3 rounded-lg text-text-secondary`}
              >
                <i className="fas fa-history text-lg"></i>
                <span className="font-medium">历史记录</span>
              </Link>
            </li>
            <li>
              <Link 
                to="/settings" 
                className={`${styles.navItem} flex items-center space-x-3 px-4 py-3 rounded-lg text-text-secondary`}
              >
                <i className="fas fa-cog text-lg"></i>
                <span className="font-medium">设置</span>
              </Link>
            </li>
          </ul>
        </nav>
      </aside>

      {/* 主内容区 */}
      <main className="ml-60 mt-16 p-6 min-h-screen">
        {/* 页面头部 */}
        <div className="flex items-center justify-between mb-8">
          <div>
            <h2 className="text-2xl font-bold text-text-primary">添加食物</h2>
            <nav className="flex items-center space-x-2 text-sm text-text-secondary mt-1">
              <span>食物搜索</span>
            </nav>
          </div>
        </div>

        {/* 输入方式切换区 */}
        <div className="flex space-x-4 mb-8" role="tablist">
          <button 
            className={`px-6 py-3 text-sm font-medium rounded-lg focus:outline-none ${
              activeTab === 'text-search' ? styles.tabActive : styles.tabInactive
            }`}
            role="tab" 
            onClick={() => handleTabChange('text-search')}
          >
            <i className="fas fa-search mr-2"></i>文字搜索
          </button>
          <button 
            className={`px-6 py-3 text-sm font-medium rounded-lg focus:outline-none ${
              activeTab === 'image-recognition' ? styles.tabActive : styles.tabInactive
            }`}
            role="tab" 
            onClick={() => handleTabChange('image-recognition')}
          >
            <i className="fas fa-camera mr-2"></i>图片识别
          </button>
          <button 
            className={`px-6 py-3 text-sm font-medium rounded-lg focus:outline-none ${
              activeTab === 'food-library' ? styles.tabActive : styles.tabInactive
            }`}
            role="tab" 
            onClick={() => handleTabChange('food-library')}
          >
            <i className="fas fa-archive mr-2"></i>常见食物库
          </button>
        </div>

        {/* 文字搜索区 */}
        {activeTab === 'text-search' && (
          <div className="bg-white rounded-2xl shadow-card p-6">
            <div className="flex space-x-4 mb-6">
              <div className="flex-1 relative">
                <input 
                  type="text" 
                  placeholder="输入食物名称搜索..." 
                  value={textSearchInput}
                  onChange={(e) => setTextSearchInput(e.target.value)}
                  onKeyPress={handleTextSearchKeyPress}
                  className="w-full pl-10 pr-4 py-3 border border-border-light rounded-lg focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"
                />
                <i className="fas fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-text-secondary"></i>
              </div>
              <button 
                onClick={handleTextSearch}
                className="bg-primary text-white px-6 py-3 rounded-lg hover:bg-indigo-600 transition-colors"
              >
                搜索
              </button>
            </div>
            
            <div className="space-y-3">
              {textSearchInput.trim() === '' ? (
                <p className="text-text-secondary text-center py-4">请输入食物名称进行搜索</p>
              ) : searchResults.length === 0 ? (
                <p className="text-text-secondary text-center py-4">未找到相关食物</p>
              ) : (
                searchResults.map(renderFoodItem)
              )}
            </div>
          </div>
        )}

        {/* 图片识别区 */}
        {activeTab === 'image-recognition' && (
          <div className="bg-white rounded-2xl shadow-card p-6">
            <div 
              className={`${styles.uploadArea} ${isDragOver ? styles.uploadAreaDragover : ''} rounded-lg p-8 text-center mb-6 cursor-pointer`}
              onClick={handleUploadAreaClick}
              onDragOver={handleDragOver}
              onDragLeave={handleDragLeave}
              onDrop={handleDrop}
            >
              <i className="fas fa-cloud-upload-alt text-4xl text-text-secondary mb-4"></i>
              <p className="text-text-primary font-medium mb-2">点击上传或拖拽图片到此处</p>
              <p className="text-text-secondary text-sm">支持 JPG、PNG 格式，文件大小不超过 5MB</p>
              <input 
                type="file" 
                ref={imageUploadRef}
                accept="image/*" 
                className="hidden"
                onChange={handleFileChange}
              />
            </div>
            
            {selectedImage && (
              <div className="mb-6">
                <img 
                  src={selectedImage} 
                  alt="预览图片" 
                  className="max-w-md mx-auto rounded-lg"
                />
                <button 
                  onClick={handleRemoveImage}
                  className="mt-2 text-danger hover:text-red-600 text-sm"
                >
                  <i className="fas fa-times mr-1"></i>移除图片
                </button>
              </div>
            )}
            
            <button 
              onClick={handleStartRecognition}
              disabled={!selectedImage}
              className="bg-secondary text-white px-6 py-3 rounded-lg hover:bg-green-600 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
            >
              <i className="fas fa-magic mr-2"></i>开始识别
            </button>
            
            {recognitionResults.length > 0 && (
              <div className="mt-6 space-y-3">
                {recognitionResults.map(renderRecognitionResult)}
              </div>
            )}
          </div>
        )}

        {/* 常见食物库区 */}
        {activeTab === 'food-library' && (
          <div className="bg-white rounded-2xl shadow-card p-6">
            <div className="flex space-x-6">
              {/* 分类导航 */}
              <div className="w-48 space-y-2">
                {Object.entries(categoryNames).map(([category, name]) => (
                  <button 
                    key={category}
                    className={`w-full text-left px-4 py-3 rounded-lg text-sm font-medium transition-colors ${
                      activeCategory === category ? styles.categoryItemActive : styles.categoryItem
                    }`}
                    onClick={() => handleCategoryChange(category as FoodCategory)}
                  >
                    {name}
                  </button>
                ))}
              </div>
              
              {/* 食物列表 */}
              <div className="flex-1 space-y-3">
                {getFilteredFoods().map(renderFoodItem)}
              </div>
            </div>
          </div>
        )}
      </main>
    </div>
  );
};

export default FoodSearchPage;

